package cn.com.cfae.iras.doc.analyze.components.integrity;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import cn.com.cfae.iras.doc.analyze.parse.model.PageModel;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 架构完整性
 * 检查簿记建档安排≥3行
 * 发行阶段
 */
@Component("I1019")
@Scope("prototype")
public class I1019 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(I1019.class);
    @Autowired
    private HandingData handingData;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取I1019组件M");
        List<ComponentResult> componentResults = checkRulesI1019(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取I1019组件BM");
        List<ComponentResult> componentResults = checkRulesI1019(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取I1019组件DM");
        List<ComponentResult> componentResults = checkRulesI1019(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取I1019组件BDM");
        List<ComponentResult> componentResults = checkRulesI1019(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    private List<ComponentResult> checkRulesI1019(String model,String catalogId,String chapterId,String ruleName){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;
        List<ComponentResult.TextPosition> contentAndPositionList =new ArrayList<>();
        ComponentResult.TextPosition contentAndPosition =null;
        boolean flag = false;
        int jdapPageSize = 0;
        int jdapPageNum = 0;
        int jdapRow = 0;
        int fxapPageSize=0;
        int fxapPageNum = 0;
        int fxapRow = 0;
        Double x = 0.0;
        Double y = 0.0;
        boolean jdapFlag = false;
        boolean fxapFlag = false;
        int startPage = 0;
        String jdregex = ".*簿记建档安排.*";
        String fxregex =  ".*分销安排.*";
        Pattern pattern = null;
        Matcher matcher = null;
        try {

            if (extractData!=null) {
                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPage = chapterModel!=null?chapterModel.getStartPage():0;
                if (chapterModel!=null){
                    List<PageModel> pageModelList = chapterModel.getPageModelList();
                    if (CollectionUtils.isNotEmpty(pageModelList)){
                        for (PageModel pageModel:pageModelList){
                            JsonElement jsonTextData = pageModel.getJsonTextData();
                            if (!jsonTextData.isJsonNull()){
                                JsonArray jsonArray = jsonTextData.getAsJsonArray();
                                if (!jsonArray.isJsonNull()){
                                    for (int i=0;i<jsonArray.size();i++){
                                        JsonObject asJsonObject = jsonArray.get(i).getAsJsonObject();
                                        Set set = asJsonObject.entrySet();
                                        Iterator<Map.Entry<String, JsonElement>> it = set.iterator();
                                        String key ;

                                        while (it.hasNext()){
                                            //每一页data数据
                                            Map.Entry<String, JsonElement> entry = it.next();
                                            key= entry.getKey();
                                            if (StringUtils.isNotEmpty(key)&&key.equals("data")){
                                                JsonArray dataJsonArray = null;
                                                if (entry.getValue().isJsonArray()){
                                                    dataJsonArray  = entry.getValue().getAsJsonArray();
                                                }
                                                if (!dataJsonArray.isJsonNull()){

                                                    for (int d=0; d<dataJsonArray.size(); d++){
                                                        JsonArray delmJsonArray = dataJsonArray.get(d).getAsJsonArray();
                                                        if (!dataJsonArray.isJsonNull()){
                                                            for (int de=0;de<delmJsonArray.size();de++){
                                                                JsonObject deJsonObject = delmJsonArray.get(de).getAsJsonObject();
                                                                Set deSet = deJsonObject.entrySet();
                                                                Iterator<Map.Entry<String, JsonElement>> deIt = deSet.iterator();
                                                                while (deIt.hasNext()){
                                                                    Map.Entry<String, JsonElement> deEntry = deIt.next();
                                                                    String deKey= deEntry.getKey();
                                                                    if (StringUtils.isNotEmpty(deKey)&&deKey.equals("top")){
                                                                        y = deEntry.getValue()!=null?deEntry.getValue().getAsDouble():0.0;
                                                                    }
                                                                    if (StringUtils.isNotEmpty(deKey)&&deKey.equals("left")){
                                                                        x = deEntry.getValue()!=null?deEntry.getValue().getAsDouble():0.0;
                                                                    }
                                                                    if (StringUtils.isNotEmpty(deKey)&&deKey.equals("text")){

                                                                        if (!jdapFlag){
                                                                            pattern = Pattern.compile(jdregex);
                                                                            matcher = pattern.matcher(deEntry.getValue().getAsString());
                                                                            if (matcher.matches()){
                                                                                jdapPageSize  = dataJsonArray.size();
                                                                                jdapPageNum =pageModel.getPageNumber();
                                                                                jdapRow = d;
                                                                                contentAndPosition =  new ComponentResult().new TextPosition();
                                                                                contentAndPosition.setX(x);
                                                                                contentAndPosition.setY(y);
                                                                                contentAndPosition.setContent(deEntry.getValue().getAsString());
                                                                                contentAndPositionList.add(contentAndPosition);
                                                                                jdapFlag = true;
                                                                            }
                                                                        }
                                                                        if (!fxapFlag){
                                                                            pattern = Pattern.compile(fxregex);
                                                                            matcher = pattern.matcher(deEntry.getValue().getAsString());
                                                                            if (matcher.matches()){
                                                                                fxapPageSize = dataJsonArray.size();
                                                                                fxapPageNum =pageModel.getPageNumber();
                                                                                fxapRow = d;
                                                                                fxapFlag = true;
                                                                            }
                                                                        }

                                                                    }
                                                                }
                                                                if (jdapFlag && fxapFlag){
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                        if (jdapFlag && fxapFlag){
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            if (jdapFlag && fxapFlag){
                                                break;
                                            }
                                        }
                                        if (jdapFlag && fxapFlag)
                                            break;
                                    }
                                }
                            }
                            if (jdapFlag && fxapFlag)
                                break;
                        }
                    }
                }
                //有建档安排
                if (jdapFlag&&fxapFlag){
                    if (jdapPageNum == fxapPageNum){
                        if (jdapRow < fxapRow){
                            if (fxapRow - jdapRow >=3){
                                flag = true;
                            }
                        }else if (jdapRow > fxapRow){
                            if (jdapPageSize - jdapRow >=3){
                                flag = true;
                            }
                        }
                    }else if (jdapPageNum < fxapPageNum){
                        if (jdapPageSize-jdapRow+fxapRow >=3){
                            flag = true;
                        }
                    }else if (jdapPageNum > fxapPageNum){
                        if (jdapPageSize - jdapRow >= 3){
                            flag = true;
                        }
                    }

                    if (flag){
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"检查簿记建档安排行数>=3","满足行数要求",false,getRegulationId(),jdapPageNum,contentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"检查簿记建档安排行数>=3","建议人工核对",true,getRegulationId(),jdapPageNum,contentAndPositionList,"02");
                        componentResults.add(componentResult);
                    }

                }else if (jdapFlag&&!fxapFlag){
                    if (jdapPageSize-jdapRow>=3){
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"检查簿记建档安排行数>=3","满足行数要求",false,getRegulationId(),jdapPageNum,contentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"检查簿记建档安排行数>=3","建议人工核对",true,getRegulationId(),startPage,contentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }

                }else if (!jdapFlag&&fxapFlag){
                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"检查簿记建档安排行数>=3","建议人工核对",true,getRegulationId(),startPage,contentAndPositionList,"03");
                    componentResults.add(componentResult);
                }else {
                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"检查簿记建档安排行数>=3","建议人工核对",true,getRegulationId(),startPage,contentAndPositionList,"03");
                    componentResults.add(componentResult);
                }

            }

        }catch (Exception e){
            componentResults.clear();
            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"簿记建档安排行数>=3","建议人工核对",true,getRegulationId(),startPage,contentAndPositionList,"03");
            componentResults.add(componentResult);
            log.info(e.getMessage(),e);
        }
        return  componentResults;
    }
}
